/*
Copyright 2009 Peter Krajnc, SCREENWORKER

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package
{
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	
	import mx.events.FlexEvent;
	import mx.preloaders.DownloadProgressBar;
 
    public class CustomPreloader extends DownloadProgressBar
    {
 
        [Embed(source="../assets/logo.png")]
        public var LogoClass:Class;
 
        public var logo:Bitmap;
        public var progressBar:Sprite;

        public function CustomPreloader():void
        {
            super();
            logo = new LogoClass();
            addChild(logo);
            
            progressBar = new Sprite();
            progressBar.graphics.beginFill(0xFFFFFF);
            progressBar.graphics.drawRect(0,logo.height + 10, logo.width, 10);
            progressBar.graphics.endFill();
            progressBar.scaleX = 0;
            
            addChild(progressBar);
        }
 
        public override function set preloader(preloader:Sprite):void
        {
            preloader.addEventListener(ProgressEvent.PROGRESS, onSWFDownloadProgress);
            preloader.addEventListener(Event.COMPLETE, onSWFDownloadComplete);
            preloader.addEventListener(FlexEvent.INIT_PROGRESS, onFlexInitProgress);
            preloader.addEventListener(FlexEvent.INIT_COMPLETE, onFlexInitComplete);
 
            centerPreloader();
        }	
 
        private function centerPreloader():void
        {
            x = (stageWidth / 2) - (width / 2);
            y = (stageHeight / 2) - (height / 2);
        }
 
        private function onSWFDownloadProgress(event:ProgressEvent):void
        {
            var t:Number = event.bytesTotal;
            var l:Number = event.bytesLoaded;
            var p:Number = Math.round((l/t));
            var pForAmount:int = Math.floor(p * 5);
            
            progressBar.scaleX = p;
        }
 
        private function onSWFDownloadComplete(event:Event):void
        {
            progressBar.scaleX = 1;
            
        }
 
        private function onFlexInitProgress(event:FlexEvent):void
        {
           progressBar.scaleX = 1;
        }
 
        private function onFlexInitComplete(event:FlexEvent):void
        {
           progressBar.scaleX = 1;
            dispatchEvent( new Event(Event.COMPLETE));
        }
    }

}
